//
//  xsRichTextClickView.m
//  digital_robot_demo
//
//  Created by xskj on 2024/10/16.
//

#import "xsRichTextClickView.h"

@interface xsRichTextClickView()<UITextViewDelegate>

@property (nonatomic,strong)UITextView *textView;
@property (nonatomic,strong)NSMutableParagraphStyle *paragraphStyle;
@property (nonatomic,strong)NSMutableArray *allSecondStringReangMArray;

@end

@implementation xsRichTextClickView


- (instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = UIColor.blackColor;
        
        [self xsTestKongJian];
    }
    return self;
}



// 测试TextView加入父文本
- (void)xsTestKongJian{
    
    
    
    // 将NSAttributedString应用到UITextView
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 0, self.frame.size.width - 40, self.frame.size.height-65.0)];
    textView.backgroundColor = UIColor.whiteColor;
    [self addSubview:textView];
    self.textView = textView;
    //    textView.layer.cornerRadius = 2.0;
    textView.layer.borderWidth = 2.0;
    textView.layer.borderColor = UIColor.purpleColor.CGColor;
    //    //必须禁止输入，否则点击将弹出输入键
    //    textView.editable=NO;
    //    textView.scrollEnabled=NO;
    textView.delegate=self;
    
    NSString *allStrInput = @"12.5s Hello, World!中的 56.5s 90.5s Hello, World!中的 90s df 12s 8s gksdfhhhhg 8s dd 9877712.5s 12.5s 12.5s 12.5s 12.5s 12.5s 12.5s 12.5s 99s";
    
    [self xsChangeTextWithString:allStrInput];
    
    
    
    
    UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    titleButton.backgroundColor = UIColor.clearColor;
    [self addSubview:titleButton];
    [titleButton setTitle:kLocalizedString(@"插入文本") forState:UIControlStateNormal];
    [titleButton setTitleColor:COLOR_Black33 forState:UIControlStateNormal];
    titleButton.titleLabel.font = FontMedium(16);
    [titleButton addTarget:self action:@selector(titleButton:) forControlEvents:UIControlEventTouchUpInside];
    [titleButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(textView);
        make.top.equalTo(textView.mas_bottom).offset(15.0);
        make.width.mas_equalTo(180);
        make.height.mas_equalTo(45);
    }];
    
    
    int a = 10;
    
    
}

- (void)titleButton:(UIButton *)sender{
    NSLog(@"titleButton==%@\n",sender);
    NSString *tempstr =  self.textView.text;
    
    NSString *apStr = [NSString stringWithFormat:@"%@ %@ ",tempstr,@"1.5s"];
    [self xsChangeTextWithString:apStr];
}

#pragma mark 设置富文本特定颜色并且能点击
- (void)xsChangeTextWithString:(NSString *)allStrInput{
    
    
    //获取前面是整数或者浮点数后面为s的字符串范围数组
//    NSArray *secondStrArr =  [self xsRangeWithString:allStrInput];
    // secondStrArr如果有重复只会获取到第一个  所以要用到这个方法来获取全部重复的字符串位置
    NSArray *secondStrArr =  [self xsRangeWithString:allStrInput];
    NSLog(@"secondStrArr==%@\n",secondStrArr);
    
    //NSMutableArray *allSecondStringReangMArray =  [[NSMutableArray alloc] init];
    [self.allSecondStringReangMArray removeAllObjects];
    for (NSString *searchStr in secondStrArr) {
       NSArray *tempSearchArr = [self piPeiChongFuDanCi:searchStr withAllString:allStrInput];
        [self xsSearchString:searchStr];
        if(tempSearchArr&&tempSearchArr.count>0){
            [self.allSecondStringReangMArray addObjectsFromArray:tempSearchArr];
        }
    }
    NSLog(@"allSecondStringReangMArray==%@\n",self.allSecondStringReangMArray);
    
    
     //[self calculateSubStringCount:allStrInput str:<#(NSString *)#>];
    
    self.textView.attributedText = [[NSAttributedString alloc] init];
    if(!self.paragraphStyle){
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing= 2;
        paragraphStyle.paragraphSpacing = 0.0;
        self.paragraphStyle = paragraphStyle;
    }
    
    
    NSDictionary*attributes = @{NSFontAttributeName:Font(16),
                                NSParagraphStyleAttributeName:self.paragraphStyle};
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:allStrInput attributes:attributes];

    for (int i=0; i<self.allSecondStringReangMArray.count; i++) {
        
        NSString *tempSecondeStr = self.allSecondStringReangMArray[i];
        
        NSArray *tempLocationLengthArr = [tempSecondeStr componentsSeparatedByString:@"_"];
        
        NSString *tempLocationStr = tempLocationLengthArr.firstObject;
        NSString *tempLengthStr = tempLocationLengthArr.lastObject;
        
        NSUInteger tempLocation = [tempLocationStr integerValue];
        NSUInteger tempLength = [tempLengthStr integerValue];
        
        //NSRange tempSecondeStrRange = [allStrInput rangeOfString:tempSecondeStr];
        NSRange tempSecondeStrRange = NSMakeRange(tempLocation, tempLength);
        
        
        [attributedString addAttribute:NSLinkAttributeName value:tempSecondeStr range:tempSecondeStrRange];
        
    //        UIColor *backgroundColor = [UIColor lightGrayColor];
    //        [attributedString addAttribute:NSBackgroundColorAttributeName value:backgroundColor range:tempSecondeStrRange]; // 将字符的背景设置为lightGrayColor
    }

    // 设置全部未设置的文字颜色为黑色
    [attributedString addAttribute:NSForegroundColorAttributeName value:COLOR_zbTextBlack333333 range:NSMakeRange(0,allStrInput.length)];//
    self.textView.attributedText= attributedString;
    //设置被点击字体颜色
    self.textView.linkTextAttributes = @{NSForegroundColorAttributeName:COLOR_zbTextBlue4587FF};
    
    [self.textView setNeedsDisplay];
}

#pragma mark 获取前面是整数或者浮点数后面为s的字符串范围数组(注意****这个单词重复时只匹配一次)并过滤重复字符串
- (NSArray *)xsRangeWithString:(NSString *)chartString{
    
        NSError *error = nil;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\d+(\\.\\d+)?s" options:0 error:&error];
        NSArray *matches = [regex matchesInString:chartString options:0 range:NSMakeRange(0, chartString.length)];
        
        NSMutableArray *result = [NSMutableArray array];
        for (NSTextCheckingResult *match in matches) {
            NSRange matchRange = [match range];
            NSString *matchedString = [chartString substringWithRange:matchRange];
            
            BOOL isHaveString = NO;
            for (NSString *tempSecondStr in result) {
                if([tempSecondStr isEqualToString:matchedString]){
                    isHaveString = YES;
                    break;
                }
            }
            if(!isHaveString){
                [result addObject:matchedString];
            }
        }
        return result;
}

#pragma mark 使用正则NSRegularExpression匹配重复字符串并打印位置
//// 注意匹配时 被匹配的字符(charString)需要前后有空格不认匹配不到
// 使用正则NSRegularExpression匹配重复字符串并打印位置
// charString  将要匹配的单词
// allString   要匹配字符串的全部字符
- (NSArray *)piPeiChongFuDanCi:(NSString *)charString withAllString:(NSString *)allString{
  
    // 需要匹配的字符串
    NSString *string = allString;// @"This is a test string for testing. This is a test string for testing.";
    
//    NSString *tempcharString = [[charString stringByReplacingOccurrencesOfString:@"s" withString:@""] stringByReplacingOccurrencesOfString:@"S" withString:@""];
    // 需要匹配的模式
    NSString *pattern = [NSString stringWithFormat:@"\\b%@\\b",charString];//@"\\btest\\b";
    //^(特定字符)s$

    // 创建正则表达式对象
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];

    NSMutableArray *tempRangeMarr = [[NSMutableArray alloc] init];
    // 检查是否有错误发生
    if (error) {
        NSLog(@"Error: %@", [error localizedDescription]);
        return tempRangeMarr;
    }

    // 进行匹配，并获取所有匹配的结果
    NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];

    // 遍历所有匹配结果，并打印出匹配的位置
    for (NSTextCheckingResult *match in matches) {
        NSRange matchRange = [match range];
        //NSLog(@"Match found at %tu to %tu  length %lu", matchRange.location, matchRange.location + matchRange.length,matchRange.length);
        
        NSString *tempRangeStr = [NSString stringWithFormat:@"%lu_%lu",matchRange.location,matchRange.length];
        [tempRangeMarr addObject:tempRangeStr];
    }
    return tempRangeMarr;
}

#pragma mark 富文本点击事件
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction {
    //    if ([[URL scheme] isEqualToString:self.richText1]) {
    //        NSLog(@"富文本点击 用户协议");
    ////        WebViewVC *vc = [[WebViewVC alloc] init];
    ////        vc.url = [NSString stringWithFormat:@"%@%@", kApiBaseUrl, kAgreement];
    ////        vc.title = kString(@"用户协议");
    ////        [self.navigationController pushViewController:vc animated:YES];
    //    }
    //    else if ([[URL scheme] isEqualToString:self.richText2]) {
    //        NSLog(@"富文本点击 隐私政策");
    ////        WebViewVC *vc = [[WebViewVC alloc] init];
    ////        vc.url = [NSString stringWithFormat:@"%@%@", kApiBaseUrl, kAgreement];
    ////        vc.title = kString(@"隐私政策（暂无）");
    ////        [self.navigationController pushViewController:vc animated:YES];
    //    }
    
//    if ((characterRange.location == self.richText1Range.location)&&(characterRange.length == self.richText1Range.length)) {
//        NSLog(@"富文本点击 用户协议");
//
//        LiveWebViewController *vc = [[LiveWebViewController alloc] initWithleftTitleString:@"用户协议"];
//        vc.webUrlString = @"https://www.writemall.com/images/protocol/protocol.html";
//        vc.leftTitleStr = @"用户协议";
//        vc.isShowBackButton = YES;
//        [self.navigationController pushViewController:vc animated:YES];
//    }
//    else if ((characterRange.location == self.richText2Range.location)&&(characterRange.length == self.richText2Range.length)) {
//        NSLog(@"富文本点击 隐私政策");
//
//        LiveWebViewController *vc = [[LiveWebViewController alloc] initWithleftTitleString:@"隐私政策"];
//        vc.webUrlString = @"https://www.writemall.com/images/protocol/policy.html";
//        vc.leftTitleStr = @"隐私政策";
//        vc.isShowBackButton = YES;
//        [self.navigationController pushViewController:vc animated:YES];
//    }
    
    NSLog(@"characterRange==%@\n",NSStringFromRange(characterRange));
    NSLog(@"URL==%@\n",URL);
    
    NSArray *tempLocationLengthArr = [URL.absoluteString componentsSeparatedByString:@"_"];
    
    NSString *tempLocationStr = tempLocationLengthArr.firstObject;
    NSString *tempLengthStr = tempLocationLengthArr.lastObject;
    
    NSUInteger tempLocation = [tempLocationStr integerValue];
    NSUInteger tempLength = [tempLengthStr integerValue];
    
    //NSRange tempSecondeStrRange = [allStrInput rangeOfString:tempSecondeStr];
    NSRange findRange = NSMakeRange(tempLocation, tempLength);
    
    NSString *tempString = [self.textView.text copy];
    NSString *tempSecond6 = [tempString substringWithRange:findRange];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入停顿秒数" preferredStyle:UIAlertControllerStyleAlert];
     
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        // 配置文本输入框
        textField.placeholder = @"请输入停顿秒数";
        textField.secureTextEntry = NO; // 如果需要密码输入，将其设置为YES
    }];
     
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 获取输入的文本
        UITextField *textField = alertController.textFields.firstObject;
        textField.placeholder = [NSString stringWithFormat:@"%@",tempSecond6];
        NSString *inputText = textField.text;
        // 处理输入的文本
        NSLog(@"输入的文本: %@", inputText);
        
        if(!kStringIsEmpty(inputText)){
         
            
            
            NSString *tempString = [self.textView.text copy];
            NSLog(@"isInRange--tempString==%@\n",tempString);
            
            NSString *tempSecondString2 = inputText;
            if([tempSecondString2 containsString:@"s"]||[tempSecondString2 containsString:@"S"]){
                
            }
            else{
                tempSecondString2 = [NSString stringWithFormat:@"%@s",tempSecondString2];
            }
        
            tempString = [tempString stringByReplacingCharactersInRange:findRange withString:tempSecondString2];
        
            self.textView.text = @"";
        
            [self xsChangeTextWithString:tempString];
        }
        
    }];
     
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
     
    [alertController addAction:okAction];
    [alertController addAction:cancelAction];
    
    UITextField *textField = alertController.textFields.firstObject;
    textField.placeholder = [NSString stringWithFormat:@"%@",tempSecond6];
     
    UIViewController *tempVC = [YSHelp getCurrentVC];
    // 显示Alert视图
    [tempVC presentViewController:alertController animated:YES completion:nil];

    
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView{
    
    
    NSString *tempString = [textView.text copy];
    NSLog(@"textViewDidChange--tempString==%@\n",tempString);
    
    
    self.textView.text = @"";

    [self xsChangeTextWithString:tempString];
    
}

//- (void)textViewDidChangeSelection:(UITextView *)textView{
//    NSLog(@"textViewDidChangeSelection--textView.text==%@\n",textView.text);
//}
//
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{


    //NSLog(@"shouldChangeTextInRange--textView.text==%@\n",textView.text);
    NSLog(@"shouldChangeTextInRange--text==%@\n",text);
    NSLog(@"shouldChangeTextInRange--range==%@\n",NSStringFromRange(range));
    
    BOOL isInRange = NO;
    NSUInteger findRangeStringIndex = 0;
    NSRange findRange;
    for (int i=0; i<self.allSecondStringReangMArray.count; i++) {
        
        NSString *tempSecondeStr = self.allSecondStringReangMArray[i];
        
        NSArray *tempLocationLengthArr = [tempSecondeStr componentsSeparatedByString:@"_"];
        
        NSString *tempLocationStr = tempLocationLengthArr.firstObject;
        NSString *tempLengthStr = tempLocationLengthArr.lastObject;
        
        NSUInteger tempLocation = [tempLocationStr integerValue];
        NSUInteger tempLength = [tempLengthStr integerValue];
        
        //NSRange tempSecondeStrRange = [allStrInput rangeOfString:tempSecondeStr];
        NSRange tempSecondeStrRange = NSMakeRange(tempLocation, tempLength);
        
        isInRange = NSLocationInRange(range.location, tempSecondeStrRange);
        if(isInRange){
            findRange = tempSecondeStrRange;
            findRangeStringIndex = i;
            break;
        }
    }
    if(isInRange){
        [self.allSecondStringReangMArray removeObjectAtIndex:findRangeStringIndex];
        
            NSString *tempString = [self.textView.text copy];
            NSLog(@"isInRange--tempString==%@\n",tempString);
        
        tempString = [tempString stringByReplacingCharactersInRange:findRange withString:@""];
        
            self.textView.text = @"";
        
            [self xsChangeTextWithString:tempString];
        
        return NO;
    }
    else{
        
//        NSString *tempString = [self.textView.text copy];
//        NSLog(@"isInRange--tempString==%@\n",tempString);
//        self.textView.text = @"";
//        //NSString *str = @"Hello World ";
//        BOOL hasTrailingSpace = [tempString hasSuffix:@"s"];
//         
//        if (!hasTrailingSpace) {
//            NSLog(@"字符串末尾没有s");
//            
//        } else {
//            
//            //NSLog(@"字符串末尾有s");
//            tempString = [NSString stringWithFormat:@"%@ ",tempString];
//        }
//        self.textView.text = tempString;//[NSString stringWithFormat:@"%@%@",tempString,text];
        
        return YES;
    }

    //return YES;
}

- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    [color setFill];
    UIRectFill(rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
//这段代码会计算出searchString在UITextView中的位置和大小。position是字符串的左上角在UITextView中的位置，size是字符串的宽度和高度。记得替换textView和searchString为你实际的UITextView实例和要查找的字符串。
- (void)xsSearchString:(NSString *)searchString{
//    // 假设你已经有一个UITextView实例叫textView，和要查找的字符串叫searchString
//    //NSString *searchString = @"要查找的文字";
//    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.textView.attributedText];
//    NSDictionary *attributes = @{ NSFontAttributeName: Font(16) };//self.textView.font
//     
//    // 创建布局管理器和文本容器
//    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
//    [attributedString addAttribute:NSFontAttributeName value:self.textView.font range:NSMakeRange(0, attributedString.length)];
//
//    [layoutManager addTextContainer:[self.textView textContainer]];
//     
//    // 创建搜索字符串的属性文本
//    NSMutableAttributedString *searchAttributedString = [[NSMutableAttributedString alloc] initWithString:searchString attributes:attributes];
//     
//    // 创建搜索范围的位置
//    NSTextStorage *storage = [[NSTextStorage alloc] initWithAttributedString:searchAttributedString];
//    __block NSRange foundRange;
//    [storage enumerateAttributesInRange:NSMakeRange(0, searchAttributedString.length) options:0 usingBlock:^(NSDictionary * _Nonnull attributes, NSRange range, BOOL * _Nonnull stop) {
//        foundRange = range;
//        *stop = YES;
//    }];
//     
//    // 获取字符位置和大小
//    CGRect firstRect = [layoutManager boundingRectForGlyphRange:foundRange inTextContainer:[self.textView textContainer]];
//    CGPoint position = firstRect.origin;
////    position = [textView convertPoint:position fromTextView:nil];
//    position =  [self.textView convertPoint:position toView:nil];
//    CGSize size = firstRect.size;
//     
//    // 现在你有了位置(position)和大小(size)
//    NSLog(@"position--==%@\n",NSStringFromCGPoint(position));
//    NSLog(@"size--==%@\n",NSStringFromCGSize(size));
    
    
    
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (NSMutableArray *)allSecondStringReangMArray{
    if(!_allSecondStringReangMArray){
        _allSecondStringReangMArray = [[NSMutableArray alloc] init];
    }
    return _allSecondStringReangMArray;
}

@end
